package com.oplink.webbase.modules.cfg.services;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.oplink.webbase.common.persistence.Page;
import com.oplink.webbase.modules.cfg.dao.CfgNeDao;
import com.oplink.webbase.modules.cfg.entity.CfgCard;
import com.oplink.webbase.modules.cfg.entity.CfgNe;
import com.oplink.webbase.modules.cfg.entity.CfgSlot;

/**
 * 网元
 * 
 * @author yizhang
 */
@Component
@Transactional
public class CfgNeService {

	@Autowired
	private CfgNeDao neDao;

	public List<CfgNe> getAllNe() {
		return (List<CfgNe>) neDao.findAll();
	}

	public CfgNe getOneCfgNe(Long id) {
		CfgNe ne = neDao.findOne(id);
		return ne;
	}

	public Page<CfgNe> find(Page<CfgNe> page, CfgNe ne) {
		DetachedCriteria dc = neDao.createDetachedCriteria();
		// 添加查询条件
		if (StringUtils.isNotEmpty(ne.getNename())) {
			dc.add(Restrictions.like("nename", "%" + ne.getNename() + "%"));
		}
		/* dc.add(Restrictions.eq(Index.DEL_FLAG, Index.DEL_FLAG_NORMAL)); */
		dc.addOrder(Order.desc("nid"));
		return neDao.find(page, dc);
	}

	public CfgNe getCfgNe(Long id) {
		return neDao.findOne(id);
	}

	public List<CfgSlot> getSlotByNid(Long neId) {
		CfgNe ne = getCfgNe(neId);
		List<CfgSlot> listOut = new ArrayList<CfgSlot>();
		if (ne != null) {
			List<CfgSlot> listTemp = ne.getSlotlist();
			for (CfgSlot slot : listTemp) {
				if (slot.getCard() != null) {
					listOut.add(slot);
				}
			}
		}
		return listOut;
	}

	/**
	 * 通过网元ID，槽位ID定位该槽位的板卡
	 * 
	 * @param neId
	 * @param sId
	 * @return
	 */
	public CfgCard getCardByNid(Long neId, Long sId) {
		CfgNe ne = getCfgNe(neId);
		if (ne != null) {
			List<CfgSlot> listTemp = ne.getSlotlist();
			for (CfgSlot slot : listTemp) {
				if ((slot.getCard() != null) && (slot.getNum() == sId)) {
					return slot.getCard();
				}
			}
		}
		return null;
	}

	public Long save(CfgNe entity) {
		return neDao.save(entity).getNid();
	}

	public void delete(Long id) {
		neDao.delete(id);
	}

	public List<CfgNe> findAllNeBySite(long sid) {
		DetachedCriteria dc = neDao.createDetachedCriteria();
		dc.add(Restrictions.eq("site.sid", sid));
		return neDao.find(dc);
	}

	public CfgNe getByName(String name) {
		return neDao.getByName(name);
	}

	public List<CfgNe> getByIP(String name) {
		return neDao.getByIPList(name);
	}
}
